/*
*pengyangchun
*/
package com.jspgou.cms.action.directive;

import static com.jspgou.cms.Constants.SHOP_SYS;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;

import com.jspgou.cms.action.directive.abs.WebDirective;
import com.jspgou.cms.entity.Discuss;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.manager.DiscussMng;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.common.page.Pagination;
import com.jspgou.common.web.freemarker.DirectiveUtils;
import com.jspgou.core.entity.Member;
import com.jspgou.core.entity.Website;
import com.jspgou.core.manager.WebsiteMng;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class DiscussPageDirective extends WebDirective{
	
	/**
	 * 模板名称
	 */
	public static final String TPL_NAME = "ArticlePage";
	
	@SuppressWarnings("unchecked")
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		Website web = getWeb(env, params, websiteMng);
		Long memberId=getLong("memberId", params);
		Long productId=getLong("productId", params);
		Long storeId=getLong("storeId", params);
		//获取前台传来的参数，评价类型，用于按类型显示评价数据
		String discussType=getString("discussType", params);
		Pagination pagination =discussMng.getPage(memberId,productId,storeId,discussType,getPageNo(env), getCount(params), isStart(params));
		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		paramWrap.put(OUT_PAGINATION, ObjectWrapper.DEFAULT_WRAPPER.wrap(pagination));
		paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(pagination.getList()));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
		if (isInvokeTpl(params)) {
			includeTpl(SHOP_SYS, TPL_NAME, web, params, env);
		} else {
			renderBody(env, loopVars, body);
		}
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}
	
	private void renderBody(Environment env, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {
		body.render(env.getOut());
	}
	
	protected Boolean isStart(Map<String, TemplateModel> params)throws TemplateException {
        Boolean start = true;
        if(getBool("start", params)!=null){
        	if(getBool("start", params).equals(false)){
        		start = false;
        	}
        }
		return start;
    }
	
	@Autowired
	private WebsiteMng websiteMng;
	@Autowired
	private DiscussMng discussMng;

}
